package frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Calculator extends JFrame implements ActionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField displayer;
	private String s=null;
	private boolean isNewNum=true;
	private double a=0;
	public Calculator (){
		setSize(300, 280);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLayout(new BorderLayout());
		KongJian();
	}

	private void KongJian() {
		JPanel top=new JPanel();
		add(top, BorderLayout.NORTH);
		displayer=new JTextField();  
		top.setLayout(new BorderLayout());
		top.add(displayer);
		displayer.setEnabled(false);
		displayer.setHorizontalAlignment(JTextField.RIGHT);
		displayer.setFont(new Font("Consolas", Font.BOLD, 40));
		displayer.setDisabledTextColor(Color.DARK_GRAY);
		displayer.setText("0");
		JButton clear=new JButton("Clear");
		clear.addActionListener(this);
		top.add(clear, BorderLayout.EAST);
		String []fu={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","=","/"};
		JPanel center=new JPanel();
		center.setLayout(new GridLayout(4,4));
		add(center, BorderLayout.CENTER);
		for (String s : fu) {
			JButton b=new JButton(s);
			b.addActionListener(this);
			center.add(b);
			b.setFont(new Font("Consolas", Font.TRUETYPE_FONT, 20));
		}
	}
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				new Calculator();
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String txt=e.getActionCommand();
		if(".0123456789".indexOf(txt)>=0){
			showNum(txt);
		}
		else if(txt.equals("Clear")){
			displayer.setText("0");
			isNewNum=true;
			a=0;s=null;
		}
		else{
			isNewNum=true;
			SuanShi(e.getActionCommand());
		}
	}

	private void SuanShi(String f) {
		double b=Double.valueOf(displayer.getText());
		if(s!=null)
		{
			switch(s)
			{
			case"+":a=a+b;break;
			case"*":a=a*b;break;
			case"-":a=a-b;break;
			case"/":a=a/b;break;
			}
			displayer.setText(String.valueOf(a));
		}			
		else{
			a=b;
		}
		s=f;
	}

	private void showNum(String txt) {
		if(isNewNum==true)
			displayer.setText("0");
			String yTxt=displayer.getText();
			double yNum=Double.valueOf(yTxt);
			if(yNum==0&&yTxt.indexOf(".")<0){
				if(txt.equals("."))
					displayer.setText("0.");
				else displayer.setText(txt);
			}
			else{
				if(yTxt.indexOf(".")<0||!txt.equals("."))
				displayer.setText(yTxt+txt);
			}
			isNewNum=false;
		
	}
	
}
